﻿using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace SCIENEW
{
	public class ComponentSteamEngineV : ComponentInventoryTankBase, IUpdateable, IEngineComponent
	{
		public UpdateOrder UpdateOrder => UpdateOrder.Default;
		protected float m_fireTimeRemaining;
		protected float m_heatLevel;
		public float m_speed = 1f;
		public float waterConsumingSpeed = 16 / 300f;
		public float HeatLevel => m_heatLevel;
		public float FireTimeRemaining => m_fireTimeRemaining;
		public bool start;

		public SubsystemTerrain m_subsystemTerrain;

        public int FuelSlotIndex { get; set; } = 0;

		public override int GetSlotCapacity(int slotIndex, int value)
		{
            if (slotIndex == FuelSlotIndex) {
                return BlocksManager.Blocks[Terrain.ExtractContents(value)].GetFuelHeatLevel(value) > 0f ? base.GetSlotCapacity(slotIndex, value) : 0;
            }
            return base.GetSlotCapacity(slotIndex, value);
        }


		public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap)
		{
			base.Load(valuesDictionary, idToEntityMap);
			m_tanks[0].Capacity = 16;
			m_fireTimeRemaining = valuesDictionary.GetValue("FireTimeRemaining", 0f);
			m_heatLevel = valuesDictionary.GetValue("HeatLevel", 0f);
			m_subsystemTerrain = Project.FindSubsystem<SubsystemTerrain>(true);
			start = valuesDictionary.GetValue("Start", true);
		}

		public override void Save(ValuesDictionary valuesDictionary, EntityToIdMap entityToIdMap)
		{
			base.Save(valuesDictionary, entityToIdMap);
			valuesDictionary.SetValue("FireTimeRemaining", m_fireTimeRemaining);
			valuesDictionary.SetValue("HeatLevel", m_heatLevel);
			valuesDictionary.SetValue("Start", start);
		}

		public void Update(float dt)
		{
			if (m_fireTimeRemaining <= 0f) //没有燃烧时间了
			{
				if (m_heatLevel > 0) m_heatLevel = 0; //无燃烧时间，燃料等级归零

				if (GetSlotCount(0) > 0 && start) //燃料添加逻辑
				{
					int value = GetSlotValue(0);
					Block block = BlocksManager.Blocks[Terrain.ExtractContents(value)];
					if (block.GetFuelFireDuration(value) > 0
						&& HasWater()) //放入的是正确的燃料，并且水量大于0
					{
						m_fireTimeRemaining = block.GetFuelFireDuration(value);
						m_heatLevel = block.GetFuelHeatLevel(value);
						m_slots[0].Count--;
					}
				}
			}
			else //有燃烧时间
			{
				if (HasWater() && start) //水量大于0，执行蒸汽机逻辑
				{
					m_fireTimeRemaining = MathUtils.Max(0, m_fireTimeRemaining - dt*m_speed);
					m_tanks[0].Volume = MathUtils.Max(0, m_tanks[0].Volume - dt * waterConsumingSpeed);
				}
				else
				{
					m_fireTimeRemaining = 0;
				}
			}
		}

		bool HasWater() => GetTankValue(0) == FluidsManager.GetFluidID("WaterFluid", 0) && GetTankVolume(0) > 0;

		public new bool IsPowering() => m_heatLevel > 0;
	}
}